package com.xinchao.ck_mips.widgets;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Outline;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.xinchao.ck_mips.R;
import com.xinchao.ck_mips.utils.GlideTool;
import com.xinchao.player.IRenderView;
import com.xinchao.player.IjkVideoView;
import com.xinchao.player.SurfaceRenderView;
import com.xinchao.rxtools.rxhttp.tools.IDisposable;
import com.xinchao.rxtools.rxhttp.tools.RxAndroidTools;
import com.xinchao.rxtools.rxhttp.tools.RxSubscriber;

import net.lucode.hackware.magicindicator.buildins.circlenavigator.CircleNavigator;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import pl.droidsonroids.gif.GifImageView;
import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * Created by zhangbw on 2018/12/5.
 */

public class WheelPlayView extends FrameLayout {
    /**
     * 轮播文件类型-视频
     */
    public static final String FILE_TYPE_VIDEO = "video";
    /**
     * 轮播文件类型-图片
     */
    public static final String FILE_TYPE_JPEG = "jpeg";
    /**
     * 轮播文件类型-网页
     */
    public static final String FILE_TYPE_WEB = "web";
    private GifImageView mGifImageView;
    private IjkVideoView mIjkVideoView;
    private CustomVideoView mVideoView;
    private WebView mWebView;

    private View mIjkVideoViewBorder;
    private ArrayList<Source> mSources;
    private Context mContext;

    private int mIndex = 0;
    private RxSubscriber<Long> mRxSubscriber;

    private boolean isPause = false, isPrepared = false;
    private WeakReference<IDisposable> mIDisposableWeakReference;
    private Drawable mBorderDrawable;
    private int mBorderPadding, mCornerRadius;
    private onItemClickListener mOnItemClickListener;
    private onItemChangeListener mOnItemChangeListener;
    private boolean mIsShowIndicator;
    private int mColorIndicator;
    private int mGravityIndicator;
    //private MagicIndicator mMagicIndicator;
    private CircleNavigator mCircleNavigator;
    private boolean isAddSource = false;
    //private ExecutorService mExecutorService;
    private int mSeekTo;
    public static int player = 0;

    public WheelPlayView(@NonNull Context context) {
        this(context, null);
    }

    public WheelPlayView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WheelPlayView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    public void init(Context context, AttributeSet attrs, int defStyleAttr) {
        mContext = context;
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.WheelPlayView, defStyleAttr, 0);
        mBorderDrawable = array.getDrawable(R.styleable.WheelPlayView_border);
        mBorderPadding = array.getDimensionPixelSize(R.styleable.WheelPlayView_border_padding, 0);
        mCornerRadius = array.getDimensionPixelSize(R.styleable.WheelPlayView_corner_radius, 0);
        mIsShowIndicator = array.getBoolean(R.styleable.WheelPlayView_show_indicator, false);
        mColorIndicator = array.getColor(R.styleable.WheelPlayView_color_indicator, ContextCompat.getColor(mContext, android.R.color.white));
        mGravityIndicator = array.getInt(R.styleable.WheelPlayView_gravity_indicator, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        setOnClickListener(v -> {
            if (mSources == null || mSources.size() == 0) {
                return;
            }
            if (mOnItemClickListener != null) {
                mOnItemClickListener.onItemClick(mIndex - 1 < 0 ? mSources.size() - 1 : mIndex - 1);
            }
        });
        //mExecutorService = Executors.newCachedThreadPool();
    }

    private void addGifImageView() {
        mGifImageView = new GifImageView(mContext);
        mGifImageView.setScaleType(ImageView.ScaleType.FIT_XY);
        if (mBorderDrawable != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                mGifImageView.setBackground(mBorderDrawable);
            } else {
                mGifImageView.setBackgroundDrawable(mBorderDrawable);
            }
        }
        mGifImageView.setFocusable(false);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mGifImageView.setPadding(mBorderPadding, mBorderPadding, mBorderPadding, mBorderPadding);
        addView(mGifImageView, layoutParams);
    }

    private void addWebview() {
        mWebView = new WebView(mContext);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                /*if (NetWorkUtil.isNetworkAvailable(mContext)) {
                   // Toast.makeText(mContext, "当前网络不可用", Toast.LENGTH_SHORT).show();
                }*/
                return true;
            }
        });
        if (mBorderDrawable != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                mWebView.setBackground(mBorderDrawable);
            } else {
                mWebView.setBackgroundDrawable(mBorderDrawable);
            }
        }

        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mWebView.setPadding(mBorderPadding, mBorderPadding, mBorderPadding, mBorderPadding);
        addView(mWebView, layoutParams);
    }

    private void addVideoView() {
        mVideoView = new CustomVideoView(mContext);
        mIjkVideoViewBorder = new View(mContext);
        if (mBorderDrawable != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                mIjkVideoViewBorder.setBackground(mBorderDrawable);
            } else {
                mIjkVideoViewBorder.setBackgroundDrawable(mBorderDrawable);
            }
        }

        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mVideoView.setPadding(mBorderPadding, mBorderPadding, mBorderPadding, mBorderPadding);
        addView(mVideoView, layoutParams);

        LayoutParams layoutParams2 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        addView(mIjkVideoViewBorder, layoutParams2);
    }

    private void addIjkVideoView() {
        mIjkVideoView = new IjkVideoView(mContext);
        mIjkVideoView.setSkipLoopFilter(0);
        mIjkVideoView.setFastLoad(true);
        mIjkVideoView.setFrameDrop(5);

        mIjkVideoView.setEnableAccurateSeek(true);
        mIjkVideoView.setAspectRatio(IRenderView.AR_MATCH_PARENT);
        mIjkVideoView.setFocusable(false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            SurfaceRenderView surfaceRenderView = new SurfaceRenderView(mContext);
            surfaceRenderView.setOutlineProvider(new TextureVideoViewOutlineProvider(mCornerRadius));
            surfaceRenderView.setClipToOutline(true);
            mIjkVideoView.setRenderView(surfaceRenderView);
        }

        mIjkVideoViewBorder = new View(mContext);

        if (mBorderDrawable != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                mIjkVideoViewBorder.setBackground(mBorderDrawable);
            } else {
                mIjkVideoViewBorder.setBackgroundDrawable(mBorderDrawable);
            }
        }

        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mIjkVideoView.setPadding(mBorderPadding, mBorderPadding, mBorderPadding, mBorderPadding);
        addView(mIjkVideoView, layoutParams);

        LayoutParams layoutParams2 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        addView(mIjkVideoViewBorder, layoutParams2);
    }

    /*private void changeIndicatorView() {
        if (mMagicIndicator != null) {
            mMagicIndicator.removeView(mMagicIndicator);
            removeView(mMagicIndicator);
            mMagicIndicator = null;
            mCircleNavigator = null;
        }
        mMagicIndicator = new MagicIndicator(mContext);
        mMagicIndicator.setVisibility(mIsShowIndicator ? VISIBLE : GONE);
        mCircleNavigator = new CircleNavigator(mContext);
        mCircleNavigator.setCircleCount(mSources.size());
        mCircleNavigator.setCircleColor(mColorIndicator);
        mCircleNavigator.setRadius(UIUtil.dip2px(mContext, 6D));
        mCircleNavigator.setFollowTouch(false);
        mMagicIndicator.setNavigator(mCircleNavigator);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = mGravityIndicator;
        int margins = 10;
        layoutParams.setMargins(margins, margins, margins, margins);
        addView(mMagicIndicator, layoutParams);

        if (mIsShowIndicator) {
            mMagicIndicator.post(() -> {
                if (mSources.size() > 0) {
                    try {
                        mMagicIndicator.onPageSelected(mIndex - 1 < 0 ? mSources.size() - 1 : mIndex - 1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }*/

    /**
     * 设置播放资源
     *
     * @param list
     */
    public void setSources(ArrayList<Source> list) {
        if (list == null)
            return;
        mSources = list;
        Collections.sort(mSources, (o1, o2) -> o1.getIndex().compareTo(o2.getIndex()));
        reset();
        addGifImageView();
        if (player == 0) {
            addIjkVideoView();
        } else {
            addVideoView();
        }
        addWebview();
        // changeIndicatorView();
    }

    public ArrayList<Source> getSources() {
        return mSources;
    }

    /**
     * 添加播放源
     *
     * @param source
     */
    public void addSource(Source source) {
        if (mSources != null) {
            mSources.add(source);
            // changeIndicatorView();
            isAddSource = true;
        }
    }

    /**
     * 切换播放源
     *
     * @param sources
     */
    public void changeSources(List<Source> sources) {
        if (mSources != null) {
            mSources.clear();
            mSources.addAll(sources);
            Collections.sort(mSources, (o1, o2) -> o1.getIndex().compareTo(o2.getIndex()));
            // changeIndicatorView();
            isPrepared = false;
            start(mIDisposableWeakReference.get());
        }
    }

    public void start(IDisposable disposable) {
        start(disposable, 0);
    }

    public void start(IDisposable disposable, int index) {
        start(disposable, index, 0);
    }

    public void start(IDisposable disposable, int index, int seekTo) {
        if (checkSource()) {
            throw new NullPointerException("please setSources first");
        }
        if (disposable != null)
            mIDisposableWeakReference = new WeakReference<>(disposable);
        mIndex = index;
        mSeekTo = seekTo;
        if (mIndex != 0 && mIndex >= mSources.size())
            return;
        isPause = false;
        play(0);
    }

    private void play(long delayTime) {
        interruptedPlay();
        mRxSubscriber = new RxSubscriber<Long>(mIDisposableWeakReference != null ? mIDisposableWeakReference.get() : null) {
            @Override
            protected void next(Long aLong) {
                if (isPause) return;
                advanceLoad();
            }
        };
        Flowable.timer(delayTime, TimeUnit.MILLISECONDS)
                .compose(RxAndroidTools.applySchedulers())
                .subscribe(mRxSubscriber);
    }

    public void pause() {
        isPause = true;
        isPrepared = false;
        stop();
    }

    /**
     * 暂停
     */
    private void stop() {
        if (player == 0) {
            if (mIjkVideoView != null && mIjkVideoView.isPlaying()) {
//            mExecutorService.execute(() -> mIjkVideoView.stopPlayback());
                mIjkVideoView.stopPlayback();
            }
        } else {
            if (mVideoView != null && mVideoView.isPlaying()) {
                mVideoView.stopPlayback();
            }
        }
    }

    /**
     * 暂停后播放
     */
    public void restart() {
        isPause = false;
        play(0);
    }

    /**
     * 暂停后播放
     */
    public void restartPrevious() {
        if (checkSource()) {
            if (mSources.size() <= 2) {
                play(0);
                return;
            }
            if (mIndex == 0) {
                mIndex = mSources.size() - 2;
            } else {
                mIndex -= 2;
                if (mIndex < 0) {
                    mIndex = mSources.size() - 1;
                }
            }
            play(0);
        }
    }

    /**
     * 预加载视频
     */
    private void advanceLoad() {
        if (mSources != null && mSources.size() == 0) {
            play(100);//100ms 检测一次
            return;
        }
        Source sourceNext;
        Source sourceCurrent;
        sourceCurrent = mSources.get(mIndex);
        sourceNext = mSources.get((mIndex + 1 >= mSources.size()) ? 0 : (mIndex + 1));
        switch (sourceCurrent.getType()) {//当前将要播放的资源类型
            case FILE_TYPE_JPEG:
                isPrepared = false;
                if (!isPrepared) {
                    loadJpeg(sourceCurrent.getFilePath());
                }
                mGifImageView.setVisibility(View.VISIBLE);
                mGifImageView.bringToFront();
               /* if (mMagicIndicator != null)
                    mMagicIndicator.bringToFront();*/
                // mIjkVideoView.setVisibility(View.GONE);
                // mIjkVideoViewBorder.setVisibility(View.GONE);
                ////新增
                mWebView.setVisibility(View.GONE);
                mWebView.clearHistory();
                //mWebView.destroy();
                ///
                stop();
                if (player == 0) {
                    mIjkVideoView.setOnPreparedListener(null);
                    mIjkVideoView.setOnInfoListener(null);
                } else {
                    mVideoView.setOnPreparedListener(null);
                    mVideoView.setOnInfoListener(null);
                }
                switch (sourceNext.getType()) {//下一个播放类型
                    case FILE_TYPE_JPEG://图片到图片,不预加载
                        isPrepared = false;
                        break;
                    case FILE_TYPE_WEB:
                        //isPrepared = false;
                        //图片到webview,不预加载
                        //isPrepared = false;
                        //isPrepared = true;
                        mWebView.loadUrl(sourceNext.filePath);
                        isPrepared = true;
                        break;
                    case FILE_TYPE_VIDEO://图片到视频,预加载视频
                        if (player == 0) {
                            mIjkVideoView.setOnPreparedListener(mp -> {
                                mp.start();
                                if (mSeekTo > 0) {
                                    mp.seekTo(mSeekTo);
                                    mSeekTo = 0;
                                }
                                if (sourceCurrent.getPlay_time() < 0) {
                                    mp.setLooping(true);
                                } else {
                                    mp.setLooping(false);
                                }
                            });
                            mIjkVideoView.setOnInfoListener((mp, what, extra) -> {
                                if (what == IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                                    mp.pause();
                                    isPrepared = true;
                                }
                                // return isPrepared;
                                return false;
                            });
                            mIjkVideoView.setVideoPath(sourceNext.getFilePath());
                        } else {
                            mVideoView.setOnPreparedListener(mp -> {
                                mp.start();
                                if (mSeekTo > 0) {
                                    mp.seekTo(mSeekTo);
                                    mSeekTo = 0;
                                }
                                if (sourceCurrent.getPlay_time() < 0) {
                                    mp.setLooping(true);
                                } else {
                                    mp.setLooping(false);
                                }
                            });

                            mVideoView.setOnInfoListener((mp, what, extra) -> {
                                mp.pause();
                                Log.v("xika", "视频回调---1");
                                isPrepared = true;
                                return isPrepared;

                            });

                            /*mVideoView.setOnInfoListener((mp, what, extra) -> {
                                if (what == IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                                    mp.pause();
                                    Log.v("xika", "视频回调---1");
                                    isPrepared = true;
                                }
                                return false;
                            });*/

                            mVideoView.setVideoPath(sourceNext.getFilePath());
                        }
                        break;
                }

                mIndex++;
                if (mIndex >= mSources.size()) {
                    mIndex = 0;
                    if (isAddSource) {//重新排序
                        isAddSource = false;
                        Collections.sort(mSources, (o1, o2) -> o1.getIndex().compareTo(o2.getIndex()));
                    }
                }
                onItemChanged();
                if (sourceCurrent.getPlay_time() > 0) {
                    play(sourceCurrent.getPlay_time());
                }
                break;
            case FILE_TYPE_WEB:
                if (!isPrepared) {
                    mWebView.clearHistory();
                    loadWebview(sourceCurrent.getFilePath());
                }
                mWebView.setVisibility(View.VISIBLE);
                mWebView.bringToFront();
                mGifImageView.setVisibility(View.GONE);
                //mIjkVideoView.setVisibility(View.GONE);
                //mIjkVideoViewBorder.setVisibility(View.GONE);
                ////新增
                stop();
                if (player == 0) {
                    mIjkVideoView.setOnPreparedListener(null);
                    mIjkVideoView.setOnInfoListener(null);
                } else {
                    mVideoView.setOnPreparedListener(null);
                    mVideoView.setOnInfoListener(null);
                }
                switch (sourceNext.getType()) {//下一个播放类型
                    case FILE_TYPE_JPEG://web到图片,预加载
                        //isPrepared = false;
                        loadJpeg(sourceNext.getFilePath());
                        isPrepared = true;
                        break;
                    case FILE_TYPE_WEB:
                        //web到web
                        isPrepared = false;
                        //mWebView.clearHistory();
                        // mWebView.loadUrl(sourceNext.filePath);
                        break;
                    case FILE_TYPE_VIDEO://web到视频,预加载视频
                        if (player == 0) {
                            mIjkVideoView.setOnPreparedListener(mp -> {
                                mp.start();
                                if (mSeekTo > 0) {
                                    mp.seekTo(mSeekTo);
                                    mSeekTo = 0;
                                }
                                if (sourceCurrent.getPlay_time() < 0) {
                                    mp.setLooping(true);
                                } else {
                                    mp.setLooping(false);
                                }
                            });
                            mIjkVideoView.setOnInfoListener((mp, what, extra) -> {
                                if (what == IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                                    mp.pause();
                                    isPrepared = true;
                                }
                                return false;
                            });
                            mIjkVideoView.setVideoPath(sourceNext.getFilePath());
                        } else {
                            mVideoView.setOnPreparedListener(mp -> {
                                mp.start();
                                if (mSeekTo > 0) {
                                    mp.seekTo(mSeekTo);
                                    mSeekTo = 0;
                                }
                                if (sourceCurrent.getPlay_time() < 0) {
                                    mp.setLooping(true);
                                } else {
                                    mp.setLooping(false);
                                }
                            });
                            mVideoView.setOnInfoListener((mp, what, extra) -> {
                                mp.pause();
                                Log.v("xika", "视频回调-----2");
                                isPrepared = true;
                                return isPrepared;
                            });

                           /* mVideoView.setOnInfoListener((mp, what, extra) -> {
                                if (what == IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                                    mp.pause();
                                    Log.v("xika", "视频回调---2");
                                    isPrepared = true;
                                }
                                return false;
                            });*/

                            mVideoView.setVideoPath(sourceNext.getFilePath());
                        }
                        break;
                }

                mIndex++;
                if (mIndex >= mSources.size()) {
                    mIndex = 0;
                    if (isAddSource) {//重新排序
                        isAddSource = false;
                        Collections.sort(mSources, (o1, o2) -> o1.getIndex().compareTo(o2.getIndex()));
                    }
                }
                onItemChanged();
                if (sourceCurrent.getPlay_time() > 0) {
                    play(sourceCurrent.getPlay_time());
                }

                break;
            case FILE_TYPE_VIDEO:
                if (isPrepared) {
                    if (player == 0) {
                        mIjkVideoView.start();
                    } else {
                        mVideoView.start();
                    }
                    video2Next(sourceCurrent.getPlay_time(), sourceNext);
                } else {
                    if (player == 0) {
                        mIjkVideoView.setOnPreparedListener(mp -> {
                            mp.start();
                            if (mSeekTo > 0) {
                                mp.seekTo(mSeekTo);
                                mSeekTo = 0;
                            }
                            if (sourceCurrent.getPlay_time() < 0) {
                                mp.setLooping(true);
                            } else {
                                mp.setLooping(false);
                            }
                        });
                        mIjkVideoView.setOnInfoListener((mp, what, extra) -> {
                            if (what == IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                                video2Next(sourceCurrent.getPlay_time(), sourceNext);
                            }
                            return false;
                        });
                        mIjkVideoView.setVideoPath(sourceCurrent.getFilePath());
                    } else {
                        mVideoView.setOnPreparedListener(mp -> {
                            mp.start();
                            if (mSeekTo > 0) {
                                mp.seekTo(mSeekTo);
                                mSeekTo = 0;
                            }
                            if (sourceCurrent.getPlay_time() < 0) {
                                mp.setLooping(true);
                            } else {
                                mp.setLooping(false);
                            }
                        });
                        mVideoView.setOnInfoListener((mp, what, extra) -> {
                            if (what == IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                                video2Next(sourceCurrent.getPlay_time(), sourceNext);
                            }
                            return false;
                        });
                        mVideoView.setVideoPath(sourceCurrent.getFilePath());
                    }

                }
                break;
        }

    }

    /**
     * 视频到下一个
     *
     * @param play_time
     * @param sourceNext
     */
    private void video2Next(long play_time, Source sourceNext) {
        if (player == 0) {
            mIjkVideoView.setVisibility(View.VISIBLE);
            mIjkVideoViewBorder.setVisibility(View.VISIBLE);
            mIjkVideoView.bringToFront();
        } else {
            mVideoView.setVisibility(View.VISIBLE);
            mIjkVideoViewBorder.setVisibility(View.VISIBLE);
            mVideoView.bringToFront();
        }
        mIjkVideoViewBorder.bringToFront();
        /*if (mMagicIndicator != null)
            mMagicIndicator.bringToFront();*/
        mGifImageView.setVisibility(View.GONE);
        mWebView.setVisibility(View.GONE);
        switch (sourceNext.getType()) {//下一个播放类型
            case FILE_TYPE_JPEG://视频到图片，预加载图片
                loadJpeg(sourceNext.getFilePath());
                isPrepared = true;
                //isPrepared = false;
                break;
            case FILE_TYPE_VIDEO://视频到视频，不预加载
                isPrepared = false;
                break;
            case FILE_TYPE_WEB://视频到网页，预加载
                loadWebview(sourceNext.getFilePath());
                isPrepared = true;
                //isPrepared = false;
                break;
        }

        mIndex++;
        if (mIndex >= mSources.size()) {
            mIndex = 0;
            if (isAddSource) {//重新排序
                isAddSource = false;
                Collections.sort(mSources, (o1, o2) -> o1.getIndex().compareTo(o2.getIndex()));
            }
        }
        onItemChanged();
        if (play_time > 0) {
            play(play_time);
        }
    }

    /**
     * 检测资源是否存在
     *
     * @return
     */
    private boolean checkSource() {
        return mSources == null && mSources.size() == 0;
    }

    /**
     * 加载图片
     *
     * @param filePath
     */
    private void loadJpeg(String filePath) {
        GlideTool.loadImage(mGifImageView, filePath);
    }

    private void loadWebview(String url) {
        mWebView.loadUrl(url);
    }

    /**
     * 重置播放
     */
    private void reset() {
        interruptedPlay();
        mIndex = 0;
        removeAllViews();
    }

    /**
     * 中断播放
     */
    private void interruptedPlay() {
        if (mRxSubscriber != null) {
            mRxSubscriber.dispose();
            mRxSubscriber = null;
        }
    }

    public boolean isPause() {
        return isPause;
    }

    public void setBorderDrawable(Drawable drawable) {
        if (drawable == null)
            return;
        mBorderDrawable = drawable;
        changeBorder();
    }

    public void setBorderResource(@DrawableRes int drawableId) {
        setBorderDrawable(ContextCompat.getDrawable(getContext(), drawableId));
    }

    private void changeBorder() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mGifImageView.setBackground(mBorderDrawable);
            mIjkVideoViewBorder.setBackground(mBorderDrawable);
            mWebView.setBackground(mBorderDrawable);
        } else {
            mGifImageView.setBackgroundDrawable(mBorderDrawable);
            mWebView.setBackgroundDrawable(mBorderDrawable);
            mIjkVideoViewBorder.setBackgroundDrawable(mBorderDrawable);
        }
    }

    /*public void setShowIndicator(boolean isShowIndicator) {
        mIsShowIndicator = isShowIndicator;
        if (mMagicIndicator != null)
            mMagicIndicator.setVisibility(mIsShowIndicator ? VISIBLE : GONE);
        if (isShowIndicator) {
            if (mSources.size() - 1 < 0)
                return;
            try {
                mMagicIndicator.onPageSelected(mIndex - 1 < 0 ? mSources.size() - 1 : mIndex - 1);
            } catch (IndexOutOfBoundsException e) {

            }
        }
    }*/

    public void setColorIndicator(@ColorInt int colorIndicator) {
        mColorIndicator = colorIndicator;
        if (mCircleNavigator != null) {
            mCircleNavigator.setCircleColor(mColorIndicator);
        }
    }

    /**
     * 下一个
     */
    public void next() {
        play(0);
    }

    /**
     * 上一个
     */
    public void previous() {
        restartPrevious();
    }

    /**
     * 获取当前播放时间
     *
     * @return
     */
    public int getCurrentTime() {
        if (player == 0) {
            if (mIjkVideoView.getVisibility() == View.VISIBLE && mIjkVideoView.isPlaying()) {
                return mIjkVideoView.getCurrentPosition();
            } else {
                return 0;
            }
        } else {
            if (mVideoView.getVisibility() == View.VISIBLE && mVideoView.isPlaying()) {
                return mVideoView.getCurrentPosition();
            } else {
                return 0;
            }
        }
    }

    private void onItemChanged() {
        if (mSources == null || mSources.size() == 0) {
            return;
        }
        if (mOnItemChangeListener != null) {
            mOnItemChangeListener.onItemChange(mIndex - 1 < 0 ? mSources.size() - 1 : mIndex - 1);
        }
        /*if (mIsShowIndicator) {
            if (mSources.size() - 1 < 0)
                return;
            try {
                mMagicIndicator.onPageSelected(mIndex - 1 < 0 ? mSources.size() - 1 : mIndex - 1);
            } catch (IndexOutOfBoundsException e) {

            }
        }*/
    }

    public void setOnItemClickListener(onItemClickListener itemClickListener) {
        mOnItemClickListener = itemClickListener;
    }

    public void setOnItemChangeListener(onItemChangeListener itemChangeListener) {
        mOnItemChangeListener = itemChangeListener;
    }

    public interface onItemClickListener {
        void onItemClick(int position);
    }

    public interface onItemChangeListener {
        void onItemChange(int position);
    }

    /**
     * 播放源
     */
    public static class Source implements Parcelable {
        private Integer index;
        private String type;
        private String fileName;//文件名称
        private String filePath;
        private String fileUrl;
        private long play_time;
        private String version;

        public Source() {

        }

        protected Source(Parcel in) {
            if (in.readByte() == 0) {
                index = null;
            } else {
                index = in.readInt();
            }
            type = in.readString();
            fileName = in.readString();
            filePath = in.readString();
            fileUrl = in.readString();
            play_time = in.readLong();
            version = in.readString();
        }

        public static final Creator<Source> CREATOR = new Creator<Source>() {
            @Override
            public Source createFromParcel(Parcel in) {
                return new Source(in);
            }

            @Override
            public Source[] newArray(int size) {
                return new Source[size];
            }
        };

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            if (index == null) {
                dest.writeByte((byte) 0);
            } else {
                dest.writeByte((byte) 1);
                dest.writeInt(index);
            }
            dest.writeString(type);
            dest.writeString(fileName);
            dest.writeString(filePath);
            dest.writeString(fileUrl);
            dest.writeLong(play_time);
            dest.writeString(version);
        }

        public Integer getIndex() {
            return index;
        }

        public void setIndex(Integer index) {
            this.index = index;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public String getFilePath() {
            return filePath;
        }

        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }

        public String getFileUrl() {
            return fileUrl;
        }

        public void setFileUrl(String fileUrl) {
            this.fileUrl = fileUrl;
        }

        public long getPlay_time() {
            return play_time;
        }

        public void setPlay_time(long play_time) {
            this.play_time = play_time;
        }

        public String getVersion() {
            return version;
        }

        public void setVersion(String version) {
            this.version = version;
        }

        public static Creator<Source> getCREATOR() {
            return CREATOR;
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    class TextureVideoViewOutlineProvider extends ViewOutlineProvider {
        private float mRadius;

        public TextureVideoViewOutlineProvider(float radius) {
            this.mRadius = radius;
        }

        @Override
        public void getOutline(View view, Outline outline) {
            Rect rect = new Rect();
            view.getGlobalVisibleRect(rect);
            int leftMargin = 0;
            int topMargin = 0;
            Rect selfRect = new Rect(leftMargin, topMargin,
                    rect.right - rect.left - leftMargin, rect.bottom - rect.top - topMargin);
            outline.setRoundRect(selfRect, mRadius);
        }
    }
}
